package com.xms.utils;

import org.apache.poi.util.IOUtils;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * <p>
 * FileUtil
 * </p>
 *
 * @author migo
 * @since 2021/9/26
 */
public class FileUtil {
    /**
     * 不存在则创建文件夹
     *
     * @param path
     * @return
     * @throws InterruptedException
     */
    public static void mkdirIfNotExists(String path) {
        String[] paths = path.split("/");
        StringBuffer fullPath = new StringBuffer();
        for (int i = 0; i < paths.length; i++) {
            //如果是带点号的具体文件则跳过
            if(paths[i].indexOf(".") > 0) continue;
            fullPath.append(paths[i]).append("/");
            File file = new File(fullPath.toString());
            if (!file.exists()) {
                file.mkdir();
            }
        }
    }

    public static void move(String path, String dest){
        mkdirIfNotExists(dest);
        File file = new File(path);
        file.renameTo(new File(dest));
    }

    /**
     * 保存文件
     *
     * @param multipartFile
     * @param folder
     * @return
     */
    public static File saveTo(MultipartFile multipartFile, String folder) throws IOException {
        mkdirIfNotExists(folder);
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String fileExt = fileName.substring(fileName.lastIndexOf("."));
        // 用uuid作为文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String newFileName = uuid + fileExt;
        final File file = new File(folder, newFileName); //File.createTempFile(UUID.randomUUID().toString(), prefix);
        multipartFile.transferTo(file);
        return file;
    }

    /**
     * 保存文件
     *
     * @param fileItem
     * @param folder
     * @return
     * @throws Exception
     */
    public static File saveTo(FileItem fileItem, String folder) throws Exception {
        mkdirIfNotExists(folder);
        // 获取文件名
        String fileName = fileItem.getName();
        // 获取文件后缀
        String fileExt = fileName.substring(fileName.lastIndexOf("."));
        // 用uuid作为文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String newFileName = uuid + fileExt;
        final File file = new File(folder, newFileName);
        fileItem.write(file);
        return file;
    }

    public static File saveTo(InputStream stream, String fileName, String folder) throws Exception {
        mkdirIfNotExists(folder);
        // 获取文件后缀
        String fileExt = fileName.substring(fileName.lastIndexOf("."));
        // 用uuid作为文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String newFileName = uuid + fileExt;
        final File file = new File(folder, newFileName);
        try(FileOutputStream fos = new FileOutputStream(file);) {
            IOUtils.copy(stream, fos);
        }
        return file;
    }

    public static String readFile(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr);
            }
            reader.close();
            return sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return sbf.toString();
    }

    public static void writeFile(String path, String content) throws IOException {
        try(
            BufferedWriter bw = new BufferedWriter(new FileWriter(path));
        ) {
            bw.write(content);
        }
    }
}
